package light.mvc.controller.workflow;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.util.zip.ZipInputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import light.mvc.controller.base.BaseController;
import light.mvc.pageModel.base.Grid;
import light.mvc.pageModel.base.Json;
import light.mvc.pageModel.base.PageFilter;
import light.mvc.pageModel.workflow.FormTemplate;
import light.mvc.service.workflow.ProcessDefinitionServiceI;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

@Controller
@RequestMapping({ "/processDefinition" })
public class ProcessDefinitionController extends BaseController {
	@Autowired
	private ProcessDefinitionServiceI processDefinitionService;

	@RequestMapping({ "/management" })
	public String list() {
		return "/workflow/list";
	}

	@RequestMapping({ "/dataGrid" })
	@ResponseBody
	public Grid dataGrid(FormTemplate formTemplate, PageFilter ph) {
		Grid grid = new Grid();
		grid.setRows(this.processDefinitionService.findAllLatestVersions());
		grid.setTotal(Integer.valueOf(grid.getRows().size()).longValue());
		return grid;
	}

	/** 删除，也要删除对应的文件 */
	@RequestMapping({ "/delete" })
	@ResponseBody
	public Json delete(String key) {
		processDefinitionService.deleteByKey(key);
		Json json = new Json();
		json.setSuccess(true);
		return json;
	}

	/** 添加页面 */
	@RequestMapping({ "/addUI" })
	public String addUI() {
		return "/workflow/addProDef";
	}

	// 处理文件上传一
	@RequestMapping(value = "add", method = RequestMethod.POST)
	@ResponseBody
	public Json add(@RequestParam("fileUpload") CommonsMultipartFile file, String filePath, String parentId) throws IOException {
		ZipInputStream zipInputStream = new ZipInputStream(file.getInputStream());
		processDefinitionService.deployZip(zipInputStream);
		Json json = new Json();
		json.setSuccess(true);
		return json;
	}

	/** 修改页面 */
	public String editUI() {
		// 准备数据：最新的流程定义列表
		// Collection<ProcessDefinition> processDefinitionList = processDefinitionService.findAllLatestVersions();
		// ActionContext.getContext().put("processDefinitionList", processDefinitionList);

		// 准备回显的数据
		// FormTemplate formTemplate = formTemplateService.getById(model.getId());
		// ActionContext.getContext().getValueStack().push(formTemplate);

		return "saveUI";
	}

	/** 修改 */
	public String edit() {
		// 从数据库中获取原对象
		// FormTemplate formTemplate = formTemplateService.getById(model.getId());

		// 设置要修改的属性
		// formTemplate.setName(model.getName());
		// formTemplate.setProcessDefinitionKey(model.getProcessDefinitionKey());
		// if (upload != null) {
		// 1，删除老文件
		// File file = new File(formTemplate.getPath());
		/*
		 * if (file.exists()) { file.delete(); }
		 * 
		 * // 2，保存并关联新文件 String path = saveUploadFile(upload); formTemplate.setPath(path); }
		 */

		// 更新
		// formTemplateService.update(formTemplate);

		return "toList";
	}

	/** 查看流程图（xxx.png） */
	public String showProcessImage(String id) throws Exception {
		// 进行第2次URL解码
		// id = URLDecoder.decode(id, "utf-8");

		processDefinitionService.getProcessImageResourceAsStream(id);
		return "showProcessImage"; // stream
	}

	@RequestMapping(value = "showProcessImage")
	public void showProcessImage(HttpServletRequest request, HttpServletResponse response, String id, String fileName, String path) throws Exception {
		/*response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("UTF-8");
		String newFileName = new String(fileName.getBytes("ISO8859-1"), "UTF-8");
		String ctxPath = path;
		String downLoadPath = ctxPath;
		long fileLength = new File(downLoadPath).length();
		response.setHeader("Content-disposition", "attachment; filename=" + new String(newFileName.getBytes("gb2312"), "ISO8859-1"));
		response.setHeader("Content-Length", String.valueOf(fileLength));*/
		String decodeId = URLDecoder.decode(id, "utf-8");
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		InputStream inputStream = processDefinitionService.getProcessImageResourceAsStream(decodeId);
		bis = new BufferedInputStream(inputStream);
		bos = new BufferedOutputStream(response.getOutputStream());
		byte[] buff = new byte[2048];
		int bytesRead;
		while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
			bos.write(buff, 0, bytesRead);
		}
		bis.close();
		bos.close();
	}
}
